package org.galaxyworld.flycode.utils;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;
import org.galaxyworld.flycode.config.ConfigFile;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class NameUtils {

    private static final Set<String> KEYWORDS;

    static {
        String[] keywords = {
                "abstract", "assert", "boolean", "break", "byte",
                "case", "catch", "char", "class", "const",
                "continue", "default", "do", "double", "else",
                "enum", "extends", "final", "finally", "float",
                "for", "goto", "if", "implements", "import",
                "instanceof", "int", "interface", "long", "native",
                "new", "package", "private", "protected", "public",
                "return", "strictfp", "short", "static", "super",
                "switch", "synchronized", "this", "throw", "throws",
                "transient", "try", "void", "volatile", "while" };
        KEYWORDS = new HashSet<>(Arrays.asList(keywords));
    }

    /**
     * Formats Java class name.
     *
     * @param tableName the name to be formatted
     * @param prefixes prefixes
     * @param includePrefix whether need prepend the prefixes
     * @return formatted class name
     */
    public static String tableNameToClassName(String tableName, List<String> prefixes, boolean includePrefix) {
        String name = tableName;
        if (!includePrefix) {
            for (String prefix : prefixes) {
                if (StringUtils.startsWith(tableName, prefix)) {
                    name = StringUtils.substringAfter(tableName, prefix);
                    break;
                }
            }
        }
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name);
    }

    /**
     * Gets a valid variable name of Java.
     *
     * This will filter any Java keywords with '_' ahead.
     *
     * @param columnName column name
     * @return a valid variable name
     */
    public static String columnNameToMemberName(String columnName) {
        String name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
        return KEYWORDS.contains(name) ? name + ConfigFile.keywordPostfix() : name;
    }

    /**
     * Check if the column name will be converted to a Java keyword.
     *
     * @param columnName column name
     * @return true if the column name will be converted to a keyword
     */
    public static boolean isKeyword(String columnName) {
        String name = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
        return KEYWORDS.contains(name);
    }

}
